package com.sun.mybatisplus.resolver.handler;

import com.sun.mybatisplus.entity.User;
import com.sun.mybatisplus.resolver.annotation.CurrentUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 自定义参数解析器
 * 动态的为controller注入当前登陆的对象
 */

public class CurrentUserMethodsArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断当前参数类型是不是User,并且时使用注解@CurrentUser声明
        if (parameter.getParameterType().equals(User.class) && parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //动态获取当前登陆用户信息
        User user = new User(1, "admin", 22);
        return user;
    }
}
